<template>
  <div class="add">
    <el-card class="add-container">
      <el-form :model="counselorForm" :rules="rules" ref="counselorRef" label-width="100px" class="counselorForm">
        <el-form-item label="咨询师类型" prop="counselortype" >
            <el-cascader-panel :options="options" size="small" :props="props" v-model="counselorForm.counselortype" @change="change"/>
        </el-form-item>
        <el-form-item label="咨询师姓名" prop="counselorname">
          <el-input style="width: 300px" v-model="counselorForm.counselorname" placeholder="请输入咨询师姓名"></el-input>
        </el-form-item>
        <el-form-item label="咨询师价格" prop="originalprice">
          <el-input type="number" min="0" style="width: 300px" v-model="counselorForm.originalprice" placeholder="请输入咨询师价格"></el-input>
        </el-form-item>

        <el-form-item label="上架状态" prop="counselorsellstatus">
          <el-radio-group v-model="counselorForm.counselorsellstatus">
            <el-radio label="0">下架</el-radio>
            <el-radio label="1">上架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所在地区" prop="counselorrecommend">
          <el-radio-group v-model="counselorForm.counselorrecommend">
            <el-radio label="0">福州</el-radio>
            <el-radio label="1">长沙</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item required label="咨询师主图" prop="counselorcoverimg">
          <el-upload
            class="avatar-uploader"
            :action="uploadImgServer"
            accept="jpg,jpeg,png"
            :headers="{
              token: token
            }"
            :show-file-list="false"
            :before-upload="handleBeforeUpload"
            :on-success="handleUrlSuccess"
          >
            <img style="width: 100px; height: 100px; border: 1px solid #e9e9e9;" v-if="counselorForm.counselorcoverimg" :src="counselorForm.counselorcoverimg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item required label="咨询师副图" prop="counselorimg">
          <el-upload
            class="avatar-uploader"
            :action="uploadImgServer"
            accept="jpg,jpeg,png"
            :headers="{
              token: token
            }"
            :show-file-list="false"
            :before-upload="handleBeforeUploadImg"
            :on-success="handleUrlSuccessImg"
          >
            <img style="width: 100px; height: 100px; border: 1px solid #e9e9e9;" v-if="counselorForm.counselorimg" :src="counselorForm.counselorimg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="咨询师简介">
          <div ref='editor'></div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAdd()">{{ id ? '立即修改' : '立即创建' }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { reactive, ref, toRefs, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue'
import WangEditor from 'wangeditor'
import axios from '@/utils/axios'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { localGet, uploadImgServer, uploadImgsServer, hasEmoji } from '@/utils'
export default {
  name: 'Addcounselor',
  setup() {
    const { proxy } = getCurrentInstance()
    console.log('proxy', proxy)
    const editor = ref(null)
    const counselorRef = ref(null)
    const route = useRoute()
    const router = useRouter()
    const { id } = route.query
    counselortypestr:''
    const state = reactive({
      uploadImgServer,
      token: localGet('token') || '',
      id: id,
      counselorForm: {
        counselorname: '',
        originalprice: '',
        sellingprice: '',
        counselorsellstatus: '0',
        counselorcoverimg: '',
        counselortype:'',
        counselorimg:'',
        counselorrecommend: '0',
        counselorlecturer: ''
      },
      rules: {
        counselorcoverimg: [
          { required: 'true', message: '请上传主图', trigger: ['change'] }
        ],
        counselorimg: [
          { required: 'true', message: '请上传副图', trigger: ['change'] }
        ],
        counselorname: [
          { required: 'true', message: '请填写咨询师名称', trigger: ['change'] }
        ],
        originalprice: [
          { required: 'true', message: '请填写咨询师价格', trigger: ['change'] }
        ],
        sellingprice: [
          { required: 'true', message: '请填写咨询师售价', trigger: ['change'] }
        ],
        counselortype: [
          { required: 'true', message: '请填写咨询师类型', trigger: ['change'] }
        ],
      },
      props: {
          // props.
          multiple: true,

      },
      options : [
                    {
                        value: 'famil',
                        label: '婚姻家庭',
                        children: [
                        {
                            value: '1',
                            label: '婚外情',
                        },
                        {
                            value: '2',
                            label: '离婚',
                        },
                        {
                            value:  '3',
                            label: '家庭矛盾',
                        },
                        ],
                    },
                    {
                        value: 'emotion',
                        label: '情感',
                        children: [
                        {
                            value: '1',
                            label: '三角恋',
                        },
                        {
                            value: '2',
                            label: '失恋',
                        },
                        {
                            value: '3',
                            label: '感情修复',
                        },
                        ],
                    },
                    {
                        value: 'mood',
                        label: '情绪管理',
                        children: [
                        {
                            value: '1',
                            label: '情绪失控',
                        },
                        {
                            value: '2',
                            label: '心理疲劳',
                        },
                        {
                            value: '3',
                            label: '孤独',
                        },
                        ],
                    },
                    {
                        value: 'health',
                        label: '心身健康',
                        children: [
                        {
                            value: '1',
                            label: '做噩梦',
                        },
                        {
                            value: '2',
                            label: '产后抑郁症',
                        },
                        {
                            value: '3',
                            label: '强迫',
                        },
                        ],
                    }
                ]
    })
    let instance
    onMounted(() => {
      instance = new WangEditor(editor.value)
      instance.config.showLinkImg = false
      instance.config.showLinkImgAlt = false
      instance.config.showLinkImgHref = false
      instance.config.uploadImgMaxSize = 2 * 1024 * 1024 // 2M
      instance.config.uploadFileName = 'file'
      instance.config.uploadImgHeaders = {
        token: state.token
      }
      // 图片返回格式不同，需要自定义返回格式
      instance.config.uploadImgHooks = {
        // 图片上传并返回了结果，想要自己把图片插入到编辑器中
        // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式，可使用 customInsert
        customInsert: function(insertImgFn, result) {
          console.log('result', result)
          // result 即服务端返回的接口
          // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
          if (result.data && result.data.length) {
            result.data.forEach(item => insertImgFn(item))
          }
        }
      }
      instance.config.uploadImgServer = uploadImgsServer
      Object.assign(instance.config, {
        onchange() {
          console.log('change')
        },
      })
      instance.create()
      if (id) {
        axios.get(`/counselor/${id}`).then(res => {
          console.log(res);
          // const { counselor, firstCategory, secondCategory, thirdCategory } = res
          // console.log('counselor',counselor)
          const counselor = res;
          //[["famil","1"],["famil","2"],["famil","3"]]
          counselor.counselortype=counselor.counselortype.split(',').map(item=>{
            return item.split('-')
          });
     
          state.counselorForm = {
            counselorname: counselor.counselorname,
            originalprice: counselor.originalprice,
            sellingprice: counselor.sellingprice,
            counselorsellstatus: String(counselor.counselorsellstatus),
            counselorcoverimg: proxy.$filters.prefix(counselor.counselorcoverimg),
            counselortype:counselor.counselortype,
            counselorimg:proxy.$filters.prefix(counselor.counselorimg),
            counselorrecommend: String(counselor.counselorrecommend),
            counselorlecturer: counselor.counselorlecturer
          }
          console.log(proxy.$filters.prefix(counselor.counselorcoverimg)+'00');
          if (instance) {
            // 初始化咨询师详情 html
            instance.txt.html(counselor.counselordetailcontent)
          }
        })
      }
    })
    onBeforeUnmount(() => {
      instance.destroy()
      instance = null
    })
    const submitAdd = () => {
      counselorRef.value.validate((vaild) => {
        if (vaild) {
          // 默认新增用 post 方法
          change();
          let httpOption = axios.post
          let params = {
            counselorcoverimg: state.counselorForm.counselorcoverimg,
            counselordetailcontent: instance.txt.html(),
            counselorname: state.counselorForm.counselorname,
            counselorsellstatus: state.counselorForm.counselorsellstatus,
            originalprice: state.counselorForm.originalprice,
            sellingprice: state.counselorForm.sellingprice,
            counselortype:state.counselortypestr,
            counselorimg:state.counselorForm.counselorimg,
            counselorrecommend: state.counselorForm.counselorrecommend,
            counselorlecturer: state.counselorForm.counselorlecturer
          }
          if (params.counselorname.length > 128) {
            ElMessage.error('咨询师名称不能超过128个字符')
            return
          }
          console.log('params', params)
          if (id) {
            params.id = id
            // 修改咨询师使用 put 方法
            httpOption = axios.put
          }
          httpOption('/counselor', params).then(() => {
            ElMessage.success(id ? '修改成功' : '添加成功')
            router.push({ path: '/counselor' })
          })
        }
      })
    }
    const handleBeforeUpload = (file) => {
      const sufix = file.name.split('.')[1] || ''
      if (!['jpg', 'jpeg', 'png'].includes(sufix)) {
        ElMessage.error('请上传 jpg、jpeg、png 格式的图片')
        return false
      }
    }
    const handleBeforeUploadImg = (file) => {
      const sufix = file.name.split('.')[1] || ''
      if (!['jpg', 'jpeg', 'png'].includes(sufix)) {
        ElMessage.error('请上传 jpg、jpeg、png 格式的图片')
        return false
      }
    }
    const handleUrlSuccess = (val) => {
      state.counselorForm.counselorcoverimg = val.data || ''
    }
    const handleUrlSuccessImg = (val) => {
      state.counselorForm.counselorimg = val.data || ''
    }
    const change =()=>{
        // console.log(JSON.stringify(state.counselorForm.counselortype))
        let arr=JSON.parse(JSON.stringify(state.counselorForm.counselortype)).map(item=>{
           return item.join('-')
        })
        state.counselortypestr = arr.join(',')
    }
    return {
      ...toRefs(state),
      counselorRef,
      submitAdd,
      handleBeforeUpload,
      handleUrlSuccess,
      editor,
      handleUrlSuccessImg,
      handleBeforeUploadImg,
      change
    }
  }
}
</script>

<style scoped>
  .add {
    display: flex;
  }
  .add-container {
    flex: 1;
    height: 100%;
  }
  .avatar-uploader {
    width: 100px;
    height: 100px;
    color: #ddd;
    font-size: 30px;
  }
  .avatar-uploader-icon {
    display: block;
    width: 100%;
    height: 100%;
    border: 1px solid #e9e9e9;
    padding: 32px 17px;
  }
  .el-cascader-panel.is-bordered{
width: 300px;
  }
</style>